package org.acsis.jee.services;

import java.util.Date;

import org.acsis.covoiturage.services.IClientServices;
import org.acsis.covoiturage.shared.IClient;
import org.acsis.jee.dao.ClientDAO;
import org.acsis.jee.dao.DAOFactory;
import org.acsis.jee.dao.UtilisateurDAO;
import org.acsis.jee.mail.Email;
import org.acsis.jee.mail.VelocityPrinter;
import org.acsis.jee.pojo.Client;
import org.acsis.jee.pojo.Utilisateur;
import org.acsis.jee.transfert.ClientTransfert;
import org.acsis.jee.util.HibernateUtil;
import org.apache.velocity.VelocityContext;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ClientServices implements IClientServices{


	DAOFactory dao = DAOFactory.getDAOFactory(DAOFactory.HIBERNATE);
	private static final String MAIL_OBJECT = "Covoiturage - mot de passe";
	
	@Override
	public boolean passwordForgotten(String id) {
		
		UtilisateurDAO userDao = dao.getUtilisateurDAO();
		Utilisateur user = userDao.get(id);
		Client client = user.getPersonne();
		
		
		VelocityContext ctx = new VelocityContext();
		ctx.put("client", client);
		ctx.put("user", user);
		
		return Email.sendMail(client.getAdressMail(), MAIL_OBJECT, VelocityPrinter.constructText(ctx, "psw-forgotten", "UTF-8"));
	}

	@Override
	public IClient doInscription(String civilite, String nom, String prenom,
			Date ddn, String email, String id, String psw) {
		
		Client client = new Client();
		
		client.setCivilite(civilite);
		client.setDateInscription(new Date()); 
		client.setDateNaissance(ddn);
		client.setNom(nom);
		client.setPrenom(prenom);
		client.setAdressMail(email);
		
		Utilisateur user = new Utilisateur(id, psw);
		user.setPersonne(client);
		
		UtilisateurDAO userDao = dao.getUtilisateurDAO();
		
		Session s = HibernateUtil.getCurrentSession();
		Transaction trx = s.beginTransaction();
		
		userDao.create(user);
		
		s.flush();
		trx.commit();
		s.close();
		
		VelocityContext ctx = new VelocityContext();
		ctx.put("client", client);
		
		Email.sendMail(client.getAdressMail(), MAIL_OBJECT, VelocityPrinter.constructText(ctx, "inscription", "UTF-8"));
		
		return new ClientTransfert(client);
	}

}
